package spring.chatroom.java_chatroom.model.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import spring.chatroom.java_chatroom.common.handler.WebSocketHandler;
import spring.chatroom.java_chatroom.common.utils.SerializeUtil;
import spring.chatroom.java_chatroom.pojo.model.MsgInfo;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


@Slf4j
@Component
public class AiResQueue {
    static BlockingQueue<MsgInfo> queue;

    @Autowired
    WebSocketHandler webSocketHandler;

    public AiResQueue() {
        queue = new LinkedBlockingQueue<>();
        Thread thread = new Thread(() -> {
            log.info("开始监听ai回答的消息阻塞队列");
            while (true) {
                try {
                    MsgInfo take = null;
                    take = AiResQueue.take();
                //发送个接收消息的方法
                    webSocketHandler.handleMessage(null, new TextMessage(SerializeUtil.encode(take)));
                }catch (InterruptedException e) {
                    log.error("阻塞队列出现了错误：{}", e.getMessage(), e);
                }
                catch (Exception e) {
                    log.error("在获取到ai回复之后 调用websocket的handleMessage出现呢错误：{}", e.getMessage(), e);
                }

            }
        });
        thread.start();
    }

    public static void put(MsgInfo item) {
        queue.offer(item);
    }

    public static MsgInfo take() throws InterruptedException {
        return queue.take();
    }
}
